package com.TanNgee.zookeeper;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

/**
 * @author 陈毅
 * @create 2022/3/20 1:04
 */
public class ZookeeperDemo {
    private static final int BASE_SLEEP_TIME = 1000;
    private static final int MAX_RETRIES = 3;

    public static void main(String[] args) throws Exception {


// Retry strategy. Retry 3 times, and will increase the sleep time between retries.
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(BASE_SLEEP_TIME, MAX_RETRIES);
        CuratorFramework zkClient = CuratorFrameworkFactory.builder()
                // the server to connect to (can be a server list)
                .connectString("127.0.0.1:2181")
                .retryPolicy(retryPolicy)
                .build();
        zkClient.start();


//        // 创建持久化节点
//        //注意:下面的代码会报错，下文说了具体原因
//        zkClient.create().forPath("/node1");
//        zkClient.create().forPath("/node1/00001");
//        zkClient.create().withMode(CreateMode.PERSISTENT).forPath("/node1/00002");


        //  创建临时节点
//        zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/node2/00001");

//        // 创建节点并指定内容
//        zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/node1/00001", "java".getBytes());
//        zkClient.getData().forPath("/node1/00001");//获取节点的数据内容，获取到的是 byte数组


//        // 检测节点是否创建成功
//        zkClient.checkExists().forPath("/node1/00001");//不为null的话，说明节点创建成功

//        //删除一个子节点
//        zkClient.delete().forPath("/node1/00001");

        // 删除一个节点及其下的所有子节点
//        zkClient.delete().deletingChildrenIfNeeded().forPath("/node1");

//        // 获取/更新节点数据.
////        zkClient.create().creatingParentsIfNeeded().withMode(CreateMode.EPHEMERAL).forPath("/node1/00001","java".getBytes());
//        zkClient.getData().forPath("/node1/00001");//获取节点的数据内容
//        zkClient.setData().forPath("/node1/00001","c++".getBytes());//更新节点数据内容


        while (true){
            // 监听器
            String path = "/node1";
            PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, path, true);
            PathChildrenCacheListener pathChildrenCacheListener = (curatorFramework, pathChildrenCacheEvent) -> {
                // do something
                System.out.println(pathChildrenCacheEvent.getType());

            };
            pathChildrenCache.getListenable().addListener(pathChildrenCacheListener);
            pathChildrenCache.start();
        }

    }
}
